<template>
	<view class="container-u">
	  <view class="userinfo">
	    <block>
	      <open-data class="userinfo-avatar" type="userAvatarUrl"></open-data>
	      <open-data type="userNickName"></open-data>
	    </block>
	    <block v-if="!hasUserInfo">
	      <button v-if="canIUseGetUserProfile" bindtap="getUserProfile"> 获取头像昵称 </button>
	      <button v-else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
	    </block>
	   
	  </view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {},
				hasUserInfo: false,
				canIUseGetUserProfile: false,
			}
		},
		onLoad() {
			if (wx.getUserProfile) {
			      this.canIUseGetUserProfile = true
			    }
		},
		onShow() {
			if (wx.canIUse('hideHomeButton')) {
			      wx.hideHomeButton()
			    }
		},
		methods: {
			
			addUser: function (name, icon){
			   let that = this
			    var map = {
			      id: this.$common.openID,
			      flag: 'add',
			      name: name,
			      icon: icon
			    }
			    wx.request({
			      url: that.$common.serverAddr +'/OrderSys/HandleUser',
			      data: map,
			      success: function(res) {
			        console.log(res)
			       
			        if (res.data == 'no') {
			          that.$uniApi.tipMsg('用户已存在')
			        }
			        uni.switchTab({
			          url: '/pages/index/index',
			        })
			      }
			    })
			  },
			  
			   getUserProfile(e) {
			      
			      let that = this
			      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			      // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			      wx.getUserProfile({
			        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			        success: (res) => {
			          this.hasUserInfo = true
			          console.log('name '+res.userInfo.nickName)
			          that.addUser(res.userInfo.nickName, res.userInfo.avatarUrl)
			        }
			      })
			    },
				
				  getUserInfo(e) {
				    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
				    this.hasUserInfo = true
				    this.addUser(e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl)
				  }
		}
	}
</script>

<style>

.container-u {
  padding-top: 30%;
} 

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  /* border-radius: 50%; */
}

text{
  margin-top: 30%;
  text-align: center;
}

button {
  margin-top: 30%;
  margin-left: 20%;
  margin-right: 20%;
}
</style>
